package com.atkid.boot.controller;

import cn.hutool.core.date.DateUtil;
import com.atkid.boot.entity.vo.StuVo;
import com.atkid.boot.generator.ExcelGenerator;
import com.atkid.boot.service.StudentService;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/xssf")
public class XSSFController {

	@Autowired
	StudentService studentService;
	@Autowired
	ExcelGenerator excelGenerator;


	@PostMapping("/{clubId}")
	public void generateStudentXSSFByClub(@PathVariable Integer clubId,
			HttpServletResponse response) {
		List<StuVo> voList = studentService.getByClub(clubId);
		String[] titles = {"学号", "姓名", "性别", "学院", "班级", "电话", "所选社团", "时间"};
		int listSize = voList.size();
		int titleSize = titles.length;
		String[][] values = new String[listSize][titleSize];
		for (int i = 0; i < listSize; i++) {
			StuVo vo = voList.get(i);
			values[i][0] = vo.getId();
			values[i][1] = vo.getName();
			values[i][2] = vo.getSex();
			values[i][3] = vo.getDepartment();
			values[i][4] = vo.getClassName();
			values[i][5] = vo.getPhone();
			values[i][6] = vo.getClub();
			values[i][7] = DateUtil.format(vo.getTime(), "yyyy-MM-dd HH:mm:ss");
		}
		int[] widths = {25, 10, 10, 30, 15, 25,25, 40};
		XSSFWorkbook workbook = excelGenerator.generate("工作表", titles, values, widths);
		OutputStream os = null;
		// 网络流输出
		response.setContentType("application/octet-stream");
		response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
		response.setHeader("Content-disposition",
				"attachment;filename=\"" + "test.xlsx" + "\"");
		try {
			os = response.getOutputStream();
			workbook.write(os);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (os != null) {
				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
